/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.bccah.modlib.dbdo.controller
 * @Filename: AcsControlRoomInfoController.java
 * @Description: TODO(AcsControlRoomInfoController)
 * @author: 金鑫智慧
 * @date: 2020-04-07
 * @version: V1.0
 * @Copyright: 2018 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdacsrecord.core.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.*;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsBlockStatInfoVO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsControlRoomInfoVO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult2;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.ResultVO2;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlBlockInfoService;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlRoomInfoService;
import com.jinxin.platform.cdacsrecord.core.service.AcsExportService;
import com.jinxin.platform.cdacsrecord.core.service.RestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * TODO(AcsControlRoomInfoController)
 * @Classn: AcsControlRoomInfoController
 * @author SY
 * @date 2020-04-07
 */
@RestController
@RequestMapping("/basicRoom")
@Slf4j
public class AcsControlRoomInfoController {
    @Autowired
    private AcsControlBlockInfoService blockInfoService;
    @Autowired
    private AcsControlRoomInfoService roomInfoService;
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private AcsExportService exportService;

    /**
     * 获取房间信息的分页表
     * @param roomName
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("/roomTable")
    public Map getRoomTable(String roomName, int page, int limit, String community,String blockId, String blockName){
        Map<String,Object> resultMap = new HashMap<>();
        PageInfo<AcsControlRoomInfoDO> pageInfo = roomInfoService.selParamPage(page,limit,roomName,community,blockId,blockName);
        resultMap.put("code","0");
        resultMap.put("msg","");
        resultMap.put("count",pageInfo.getTotal());
        resultMap.put("data",pageInfo.getList());
        return resultMap;
    }

    /**
     * 添加房间信息
     * @param infoVO
     * @return
     */
    @PostMapping("/addRoom")
    public ResultEntity addRoomInfo(@Valid AcsControlRoomInfoVO infoVO){
        // save
        AcsControlRoomInfoDO infoDO = new AcsControlRoomInfoDO();
        BeanUtils.copyProperties(infoVO,infoDO);
        infoDO.setCreateTime(LocalDateTime.now());
        infoDO.setState("0");
        try{
            ResultVO2 resultVO = restTemplateService.buildingunitOperate(Constant.OPERATION_SIGN_ADD, infoDO);
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                infoDO.setRoomId(resultVO.getObject().toString());
                roomInfoService.saveDO(infoDO);
                log.info(infoDO.toString());
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
            }else {
                assert resultVO != null;
                return new ResultEntity(CommonCodeEntity.FAIL,resultVO.getRstDesc(),"");
            }
        }catch (Exception e ){
            log.error("addRoomInfo:",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败，请检查房间号是否重复","");
        }
    }

    /**
     * 删除楼栋信息
     * @param bid
     * @return
     */
    @PostMapping("/delRoom")
    public ResultEntity delRoom(String bid, String companyId, String blockId,String code){
        if(StringUtils.isEmpty(bid) || StringUtils.isEmpty(companyId) || StringUtils.isEmpty(blockId)){
            return new ResultEntity(CommonCodeEntity.FAIL,"id为空，删除失败","" );
        }
        if(StringUtils.isEmpty(code)){
            return new ResultEntity(CommonCodeEntity.FAIL,"小区编号为空，删除失败","" );
        }
        AcsControlRoomInfoDO roomInfoDO = new AcsControlRoomInfoDO();
        roomInfoDO.setRoomId(bid);
        roomInfoDO.setCompanyId(companyId);
        roomInfoDO.setBlockId(blockId);
        roomInfoDO.setHousingEstateId(code);
        ResultVO2 resultVO = restTemplateService.buildingunitOperate(Constant.OPERATION_SIGN_DEL, roomInfoDO);
        if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
            roomInfoService.delDO(bid);
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL, "删除失败，请稍后重试","" );
        }

    }

    /**
     * 更新房间信息
     * @param infoVO
     * @return
     */
    @PostMapping("/upRoom")
    public ResultEntity upRoom(AcsControlRoomInfoVO infoVO){
        if(StringUtils.isEmpty(infoVO.getRoomId() )){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"ROOM_ID为空","" );
        }
        AcsControlRoomInfoDO infoDO = new AcsControlRoomInfoDO();
        BeanUtils.copyProperties(infoVO,infoDO );
        try{
            ResultVO2 resultVO = restTemplateService.buildingunitOperate(Constant.OPERATION_SIGN_EDIT, infoDO);
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                log.info(infoDO.toString());
                roomInfoService.updateDO(infoDO);
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
            }else {
                assert resultVO != null;
                String desc = resultVO != null ? resultVO.getRstDesc() : "更新失败，请稍后重试";
                return new ResultEntity(CommonCodeEntity.FAIL, desc,"");
            }
        }catch (Exception e ){
            log.error("upRoom:",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"更新失败，请稍后重试","");
        }
    }

    /**
     * 根据楼栋信息查询房间号
     * @param blockId
     * @return
     */
    @PostMapping("/selRoomByBlock")
    public ResultEntity selRoomByBlock(String blockId ){
        AcsControlRoomInfoDO roomInfoDO = new AcsControlRoomInfoDO();
        if(!StringUtils.isEmpty(blockId)){
            roomInfoDO.setBlockId(blockId);
        }
        List<AcsControlRoomInfoDO> infoDOS = roomInfoService.selDOByInfo(roomInfoDO);
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",infoDOS);
    }

    /**
     * 导入房间信息
     * @param file
     * @return
     */
    @PostMapping("/uploadRoom")
    public ResultEntity uploadRoom(MultipartFile file, String community,String housingEstateId) {
        try {
            Map<String,String> resMap = roomInfoService.uploadRoom(file, community, housingEstateId);
            return new ResultEntity(resMap.get("resultCode"),resMap.get("resultDesc"),"" ) ;
        } catch (Exception e) {
            log.error("error",e);
            return new ResultEntity(CommonCodeEntity.FAIL,"格式有误或者房间号重复，请修改后重试","" );
        }
    }

    @RequestMapping("/exportRoom2Excel")
    public void exportRoom2Excel(HttpServletResponse response, String communityId){
        exportService.exportRoom2Excel(response, communityId);
    }

    @RequestMapping("/syncData")
    public ResultEntity syncData(String companyId){
        int count = 0;
        List<AcsBlockStatInfoVO> list = blockInfoService.listStatBlcokInfo(companyId);
        if(list == null || list.size() == 0){
            return new ResultEntity(CommonCodeEntity.FAIL,"无楼栋数据，同步失败","" );
        }
        try {
            int index = 0;
            List<String> idList = new ArrayList<>();
            for (AcsBlockStatInfoVO blockInfo: list) {
                if(index == 0){
                    AcsControlRoomInfoDO roomParam = new AcsControlRoomInfoDO();
                    roomParam.setCompanyId(companyId);
                    List<AcsControlRoomInfoDO> list2 = roomInfoService.selDOByInfo(roomParam);
                    for(AcsControlRoomInfoDO roomInfoDO : list2){
                        idList.add(roomInfoDO.getRoomId());
                    }
                }
                String blockId = blockInfo.getBlockId();
                ResultEntity resultEntity = restTemplateService.buildingunitSearch(1, 300, blockId, companyId);
                if(resultEntity != null && resultEntity.getResultCode().equals("000")){
                    DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
                    if(dataResult == null){
                        return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
                    }
                    List<JSONObject> jsonList = JSON.parseArray(dataResult.getRows().toString(),JSONObject.class);
                    if(jsonList != null){
                        for (JSONObject json : jsonList) {
                            WyRoomInfo roomInfo = JSON.parseObject(toJSONString(json), WyRoomInfo.class);
                            if(roomInfo != null){
                                String roomId = roomInfo.getAreaId();
                                AcsControlRoomInfoDO roomInfoDO = roomInfoService.getById(roomId);
                                if(roomInfoDO == null){
                                    roomInfoDO = new AcsControlRoomInfoDO();
                                    roomInfoDO.setRoomId(roomId);
                                    roomInfoDO.setRoomName(roomInfo.getAreaName());
                                    roomInfoDO.setRoomDesc(roomInfo.getAreaName());
                                    roomInfoDO.setBlockId(roomInfo.getParentId()+"");
                                    roomInfoDO.setBlockName(roomInfo.getParent());
                                    roomInfoDO.setCreateTime(LocalDateTime.now());
                                    roomInfoDO.setState("0");
                                    roomInfoDO.setCompanyId(companyId);
                                    roomInfoService.saveDO(roomInfoDO);
                                    count++;
                                }else {
                                    idList.remove(roomId);
                                }
                            }
                        }
                    }
                }
                index++;
            }
            for(String id : idList){
                roomInfoService.delDO(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
        }
        log.info("成功同步房间数据"+count+"条");
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"成功同步数据"+count+"条","");
    }

}
